/**
 * 
 */

package com.pp.admin.login.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.Window.Location;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.DockLayoutPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.pp.admin.common.client.LoaderBar;
import com.pp.admin.common.client.beans.BaseDomain;
import com.pp.admin.common.client.beans.LoginUserInfo;
import com.pp.admin.common.client.exceptions.InvalidDomain;
import com.pp.admin.common.client.helper.JavaScriptCommon;
import com.pp.admin.common.client.helper.QueryString;
import com.pp.admin.common.client.service.Service;

/**
 * @author pandurang
 */
public class Login implements EntryPoint, Service {
	
	private DockLayoutPanel	adminRootPanel	= null;
	
	private BaseDomain		domain			= null;
	
	private LoaderBar		progressBar		= new LoaderBar();
	
	/*
	 * (non-Javadoc)
	 * @see com.google.gwt.core.client.EntryPoint#onModuleLoad()
	 */

	/**
	 * @return the domain
	 */
	public BaseDomain getDomain() {

		return domain;
	}
	
	@Override
	public void onModuleLoad() {

		progressBar.show();
		domainService.getDomainByDomainID( QueryString.getCurrentDomain(), new AsyncCallback<BaseDomain>() {
			
			@Override
			public void onSuccess( BaseDomain result ) {

				Login.this.domain = result;
				if ( result != null ) {
					loginService.isUserLogedIn( result.getDomainID(), new AsyncCallback<LoginUserInfo>() {
						
						@Override
						public void onFailure( Throwable caught ) {

							Login.this.loadPage();
							Login.this.progressBar.hide();
							
						}
						
						@Override
						public void onSuccess( LoginUserInfo result ) {

							JavaScriptCommon.redirectToUrl( getDomainRedirectURL() );
							
						}
					} );
				} else {
					Login.this.progressBar.hide();
					loadErrorPage();
				}
			}
			
			@Override
			public void onFailure( Throwable caught ) {

				Login.this.progressBar.hide();
				if ( caught instanceof InvalidDomain ) {
					loadErrorPage();
				}
				
			}
		} );
	}
	
	private void loadErrorPage() {

		RootLayoutPanel rp = RootLayoutPanel.get();
		rp.add( new HTML( "<font color='red'><b> Invalid domain Please contact Administration Support.</b></font>" ) );
	}
	
	private void loadPage() {

		//		RootLayoutPanel.get().add( new HTML( "Query String =>" + Location.getQueryString() + " <br> Path => " + Location.getPath() ) );
		adminRootPanel = new LoginPage( Unit.EM, this );
		RootLayoutPanel rp = RootLayoutPanel.get();
		rp.add( adminRootPanel );
//		( (LoginPage) adminRootPanel ).setFocus();
		
	}
	
	public String getDomainRedirectURL() {

		return Login.this.domain.getHomeURL() + Location.getQueryString();
	}
}
